<template>
  <!--  第一页，课程基本信息  -->
  <div v-show="firstPage">
    <el-card class="p-2">
      <el-form
        :model="queryInfo"
        ref="queryFormRef"
        label-position="left"
        label-width="88px"
        :rules="rules"
      >
        <el-row>
          <el-col :span="15">
            <el-form-item label="课程名称" prop="name">
              <el-input
                v-model="queryInfo.name"
                placeholder="请输入课程名"
                clearable
                @change="firstPageSaved = false"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="15">
            <el-form-item label="副标题" prop="subtitle">
              <el-input
                v-model="queryInfo.subtitle"
                placeholder="请输入副标题"
                clearable
                @change="firstPageSaved = false"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="5">
            <el-form-item label="课程类别" prop="type">
              <el-select
                v-model="queryInfo.type"
                clearable
                placeholder="请选择"
                style="width: 200px"
                @change="firstPageSaved = false"
              >
                <el-option
                  v-for="item in selectArr.typeArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item
              label="孩子年龄"
              style="margin: 0 20px"
              prop="childAgeList"
            >
              <el-select
                v-model="(queryInfo as any).childAgeList"
                multiple
                collapse-tags
                collapse-tags-tooltip
                :max-collapse-tags="1"
                placeholder="请选择"
                style="width: 240px"
                @change="firstPageSaved = false"
              >
                <el-option
                  v-for="item in selectArr.childAgeArr"
                  :key="(item as any).id"
                  :label="(item as any).value"
                  :value="(item as any).id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="家长年龄" prop="parentAgeList">
              <el-select
                v-model="(queryInfo as any).parentAgeList"
                multiple
                collapse-tags
                collapse-tags-tooltip
                :max-collapse-tags="1"
                placeholder="请选择"
                style="width: 240px"
                @change="firstPageSaved = false"
              >
                <el-option
                  v-for="item in selectArr.parentAgeArr"
                  :key="(item as any).id"
                  :label="(item as any).value"
                  :value="(item as any).id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="15">
            <el-form-item label="解决问题" prop="introduction">
              <el-input
                v-model="(queryInfo as any).introduction"
                placeholder="请输入"
                clearable
                type="textarea"
                :autosize="{ minRows: 5, maxRows: 10 }"
                @change="firstPageSaved = false"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="15">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="queryInfo.remark"
                placeholder="请输入"
                clearable
                type="textarea"
                :autosize="{ minRows: 5, maxRows: 10 }"
                @change="firstPageSaved = false"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="15">
            <el-form-item label="章节数量" prop="totalSection">
              <el-input
                v-model.number="queryInfo.totalSection"
                placeholder="请输入章节数量"
                clearable
                min="1"
                @change="firstPageSaved = false"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="场景分类" prop="sceneId">
          <el-select
            v-model="queryInfo.sceneId"
            clearable
            placeholder="场景分类"
            style="width: 250px"
            @change="handelSceneChange"
          >
            <el-option
              v-for="item in selectArr.sceneArr"
              :key="(item as any).id"
              :label="(item as any).name"
              :value="(item as any).id"
            />
          </el-select>

          <el-select
            v-model="queryInfo.categoryId"
            clearable
            placeholder="一级分类"
            style="width: 250px; margin-left: 20px"
            @change="handelFirstCategoryChange"
            :disabled="!queryInfo.sceneId"
          >
            <el-option
              v-for="item in selectArr.categoryList"
              :key="(item as any).id"
              :label="(item as any).name"
              :value="(item as any).id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="分类标签" prop="label">
          <el-scrollbar height="140px">
            <el-card shadow="never" style="width: 520px; height: 140px">
              <template
                v-if="
                  selectArr.labelList.length && selectArr.labelList.length > 0
                "
              >
                <el-check-tag
                  :checked="(item as any).checked"
                  @change="tagChange(item)"
                  v-for="(item, index) in selectArr.labelList"
                  :key="index"
                  style="margin-right: 10px"
                  >{{ (item as any).name }}
                </el-check-tag>
              </template>
              <el-empty description="请先选择分类" v-else image-size="0" />
            </el-card>
          </el-scrollbar>
        </el-form-item>

        <el-form-item label="">
          <el-button type="primary" @click="saveCourse">保存</el-button>

          <el-button @click="handleResetCourse">重置</el-button>
          <!-- v-show="isAddedCourse" -->
          <el-button type="success" @click="next" :disabled="!firstPageSaved">
            下一步<el-icon class="el-icon--right"><ArrowRight /></el-icon>
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>

  <!--  第二页，课程封面 -->
  <div v-show="secondPage">
    <el-card class="p-2">
      <el-form
        :model="queryInfo"
        ref="imgFormRef"
        label-position="left"
        label-width="100px"
      >
        <el-row>
          <div class="section-title">
            课程封面
            <el-tooltip effect="light" :content="tips" raw-content>
              <el-icon class="ml-1" color="#5e636e"><QuestionFilled /></el-icon>
            </el-tooltip>
          </div>
        </el-row>

        <el-form-item label="封面1">
          <div class="cover1">
            <el-upload
              action="#"
              :show-file-list="false"
              list-type="picture-card"
              :limit="1"
              :auto-upload="false"
              :on-change="handleSelectCover1"
              :on-exceed="handleReselectCover1"
              ref="upload"
            >
              <el-icon v-if="!isSelectedCover1">
                <el-tooltip
                  content="选择图片"
                  placement="top"
                  :enterable="false"
                >
                  <el-button
                    link
                    type="primary"
                    icon="UploadFilled"
                    size="large"
                    v-hasPermi="['system:user:remove']"
                  ></el-button>
                </el-tooltip>
              </el-icon>
              <div
                v-else
                class="el-upload-list__item-thumbnail"
                v-html="previews1.html"
              ></div>
            </el-upload>

            <div class="image-buttons">
              <el-button
                :disabled="!isSelectedCover1 || isUploadedCover1"
                style="font-size: 14px"
                type="success"
                @click="handleUploadCover1"
              >
                <el-icon>
                  <Top />
                </el-icon>
                {{ getUploadText(isUploadedCover1) }}
              </el-button>
              <el-button
                link
                :disabled="!isSelectedCover1"
                style="font-size: 14px; margin-left: 50px"
                type="success"
                @click="handleRecropCover1"
              >
                调整
              </el-button>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="封面2">
          <div class="cover2">
            <el-upload
              action="#"
              :show-file-list="false"
              list-type="picture-card"
              :limit="1"
              :auto-upload="false"
              :on-change="handleSelectCover2"
              :on-exceed="handleReselectCover2"
              ref="upload"
            >
              <el-icon v-if="!isSelectedCover2">
                <el-tooltip
                  content="选择图片"
                  placement="top"
                  :enterable="false"
                >
                  <el-button
                    link
                    type="primary"
                    icon="UploadFilled"
                    size="large"
                    v-hasPermi="['system:user:remove']"
                  ></el-button>
                </el-tooltip>
              </el-icon>
              <div
                v-else
                class="el-upload-list__item-thumbnail"
                v-html="previews2.html"
              ></div>
            </el-upload>

            <div class="image-buttons">
              <el-button
                :disabled="!isSelectedCover2 || isUploadedCover2"
                style="font-size: 14px"
                type="success"
                @click="handleUploadCover2"
              >
                <el-icon>
                  <Top />
                </el-icon>
                {{ getUploadText(isUploadedCover2) }}
              </el-button>
              <el-button
                link
                :disabled="!isSelectedCover2"
                style="font-size: 14px; margin-left: 50px"
                type="success"
                @click="handleRecropCover2"
              >
                调整
              </el-button>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="封面3">
          <div class="cover3">
            <el-upload
              action="#"
              :show-file-list="false"
              list-type="picture-card"
              :limit="1"
              :auto-upload="false"
              :on-change="handleSelectCover3"
              :on-exceed="handleReselectCover3"
              ref="upload"
            >
              <el-icon v-if="!isSelectedCover3">
                <el-tooltip
                  content="选择图片"
                  placement="top"
                  :enterable="false"
                >
                  <el-button
                    link
                    type="primary"
                    icon="UploadFilled"
                    size="large"
                    v-hasPermi="['system:user:remove']"
                  ></el-button>
                </el-tooltip>
              </el-icon>
              <div
                v-else
                class="el-upload-list__item-thumbnail"
                v-html="previews3.html"
              ></div>
            </el-upload>

            <div class="image-buttons">
              <el-button
                :disabled="!isSelectedCover3 || isUploadedCover3"
                style="font-size: 14px"
                type="success"
                @click="handleUploadCover3"
              >
                <el-icon>
                  <Top />
                </el-icon>
                {{ getUploadText(isUploadedCover3) }}
              </el-button>
              <el-button
                link
                :disabled="!isSelectedCover3"
                style="font-size: 14px; margin-left: 50px"
                type="success"
                @click="handleRecropCover3"
              >
                调整
              </el-button>
            </div>
          </div>
        </el-form-item>

        <!-- 课程介绍 -->
        <el-form-item label="课程/书籍结构">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :limit="1"
            :on-exceed="handleExceed4"
            :on-change="handleChange4"
            ref="upload4"
          >
            <el-icon v-if="!isSelected4">
              <el-tooltip content="选择图片" placement="top" :enterable="false">
                <el-button
                  link
                  type="primary"
                  icon="UploadFilled"
                  size="large"
                  v-hasPermi="['system:user:remove']"
                ></el-button>
              </el-tooltip>
            </el-icon>
            <el-icon v-else>
              <el-tooltip content="重新选择" placement="top" :enterable="false">
                <el-button
                  link
                  type="primary"
                  icon="Refresh"
                  size="large"
                  v-hasPermi="['system:user:remove']"
                ></el-button>
              </el-tooltip>
            </el-icon>

            <template #file="{ file }">
              <div>
                <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.url"
                  alt=""
                />
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <el-tooltip
                      content="查看详情"
                      placement="top"
                      :enterable="false"
                    >
                      <el-icon><ZoomIn /></el-icon>
                    </el-tooltip>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>

          <div class="image-buttons-right">
            <el-button
              :disabled="!isSelected4 || isUploaded4"
              style="font-size: 14px"
              type="success"
              @click="handleUpload4"
            >
              <el-icon>
                <Top />
              </el-icon>
              {{ getUploadText(isUploaded4) }}
            </el-button>
          </div>

          <el-dialog v-model="dialogStatus.preview">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>

        <el-form-item label="课程/书籍介绍">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :limit="1"
            :on-exceed="handleExceed5"
            :on-change="handleChange5"
            ref="upload5"
          >
            <el-icon v-if="!isSelected5">
              <el-tooltip content="选择图片" placement="top" :enterable="false">
                <el-button
                  link
                  type="primary"
                  icon="UploadFilled"
                  size="large"
                  v-hasPermi="['system:user:remove']"
                ></el-button>
              </el-tooltip>
            </el-icon>

            <el-icon v-else>
              <el-tooltip content="重新选择" placement="top" :enterable="false">
                <el-button
                  link
                  type="primary"
                  icon="Refresh"
                  size="large"
                  v-hasPermi="['system:user:remove']"
                ></el-button>
              </el-tooltip>
            </el-icon>

            <template #file="{ file }">
              <div>
                <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.url"
                  alt=""
                />
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <el-tooltip
                      content="查看详情"
                      placement="top"
                      :enterable="false"
                    >
                      <el-icon><ZoomIn /></el-icon>
                    </el-tooltip>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>

          <div class="image-buttons-right">
            <el-button
              :disabled="!isSelected5 || isUploaded5"
              style="font-size: 14px"
              type="success"
              @click="handleUpload5"
            >
              <el-icon>
                <Top />
              </el-icon>
              {{ getUploadText(isUploaded5) }}
            </el-button>
          </div>

          <el-dialog v-model="dialogStatus.preview">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>

        <el-form-item label="推荐及提示">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :limit="1"
            :on-exceed="handleExceed6"
            :on-change="handleChange6"
            ref="upload6"
          >
            <el-icon v-if="!isSelected6">
              <el-tooltip content="选择图片" placement="top" :enterable="false">
                <el-button
                  link
                  type="primary"
                  icon="UploadFilled"
                  size="large"
                  v-hasPermi="['system:user:remove']"
                ></el-button>
              </el-tooltip>
            </el-icon>

            <el-icon v-else>
              <el-tooltip content="重新选择" placement="top" :enterable="false">
                <el-button
                  link
                  type="primary"
                  icon="Refresh"
                  size="large"
                  v-hasPermi="['system:user:remove']"
                ></el-button>
              </el-tooltip>
            </el-icon>

            <template #file="{ file }">
              <div>
                <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.url"
                  alt=""
                />
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <el-tooltip
                      content="查看详情"
                      placement="top"
                      :enterable="false"
                    >
                      <el-icon><zoom-in /></el-icon>
                    </el-tooltip>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>

          <div class="image-buttons-right">
            <el-button
              :disabled="!isSelected6 || isUploaded6"
              style="font-size: 14px"
              type="success"
              @click="handleUpload6"
            >
              <el-icon>
                <Top />
              </el-icon>
              {{ getUploadText(isUploaded6) }}
            </el-button>
          </div>

          <el-dialog v-model="dialogStatus.preview">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>

        <el-form-item label="讲师团队">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :limit="1"
            :on-exceed="handleExceed7"
            :on-change="handleChange7"
            ref="upload7"
          >
            <el-icon v-if="!isSelected7">
              <el-tooltip content="选择图片" placement="top" :enterable="false">
                <el-button
                  link
                  type="primary"
                  icon="UploadFilled"
                  size="large"
                  v-hasPermi="['system:user:remove']"
                ></el-button>
              </el-tooltip>
            </el-icon>

            <el-icon v-else>
              <el-tooltip content="重新选择" placement="top" :enterable="false">
                <el-button
                  link
                  type="primary"
                  icon="Refresh"
                  size="large"
                  v-hasPermi="['system:user:remove']"
                ></el-button>
              </el-tooltip>
            </el-icon>

            <template #file="{ file }">
              <div>
                <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.url"
                  alt=""
                />
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <el-tooltip
                      content="查看详情"
                      placement="top"
                      :enterable="false"
                    >
                      <el-icon><zoom-in /></el-icon>
                    </el-tooltip>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>

          <div class="image-buttons-right">
            <el-button
              :disabled="!isSelected7 || isUploaded7"
              style="font-size: 14px"
              type="success"
              @click="handleUpload7"
            >
              <el-icon>
                <Top />
              </el-icon>
              {{ getUploadText(isUploaded7) }}
            </el-button>
          </div>

          <el-dialog v-model="dialogStatus.preview">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>

        <el-form-item label="">
          <el-button type="success" @click="lastPage">
            <el-icon class="el-icon--left"><ArrowLeft /></el-icon>上一步
          </el-button>
          <!-- v-show="isNext" -->
          <el-button type="success" @click="next">
            下一步 <el-icon class="el-icon--right"><ArrowRight /></el-icon>
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 封面1 -->
    <el-dialog v-model="dialogStatus.isCropper1" title="图片裁剪" width="50%">
      <div style="width: 100%; height: 60vh">
        <vueCropper
          ref="cropperRef"
          :img="options1.img"
          :info="true"
          :autoCropWidth="options1.autoCropWidth"
          :autoCropHeight="options1.autoCropHeight"
          :fixedNumber="options1.fixedNumber"
          :centerBox="options1.centerBox"
          :canScale="options1.canScale"
          :infoTrue="options1.infoTrue"
          :auto-crop="options1.autoCrop"
          :fixed-box="options1.fixedBox"
          :fixed="options1.fixed"
          @realTime="realTime1"
        >
        </vueCropper>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogStatus.isCropper1 = false">取消</el-button>
          <el-button type="" @click="refreshCrop">重置</el-button>
          <el-button type="primary" @click="finishCropCover1"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 封面2 -->
    <el-dialog v-model="dialogStatus.isCropper2" title="图片裁剪" width="50%"
      >101
      <div style="width: 100%; height: 60vh">
        <vueCropper
          ref="cropperRef"
          :img="options2.img"
          :info="true"
          :autoCropWidth="options2.autoCropWidth"
          :autoCropHeight="options2.autoCropHeight"
          :fixedNumber="options2.fixedNumber"
          :centerBox="options2.centerBox"
          :canScale="options2.canScale"
          :infoTrue="options2.infoTrue"
          :auto-crop="options2.autoCrop"
          :fixed-box="options2.fixedBox"
          :fixed="options2.fixed"
          @realTime="realTime2"
        >
        </vueCropper>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogStatus.isCropper1 = false">取消</el-button>
          <el-button type="" @click="refreshCrop">重置</el-button>
          <el-button type="primary" @click="finishCropCover2"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 封面3 -->
    <el-dialog v-model="dialogStatus.isCropper3" title="图片裁剪" width="50%">
      <div style="width: 100%; height: 60vh">
        <vueCropper
          ref="cropperRef"
          :img="options3.img"
          :info="true"
          :autoCropWidth="options3.autoCropWidth"
          :autoCropHeight="options3.autoCropHeight"
          :fixedNumber="options3.fixedNumber"
          :centerBox="options3.centerBox"
          :canScale="options3.canScale"
          :infoTrue="options3.infoTrue"
          :auto-crop="options3.autoCrop"
          :fixed-box="options3.fixedBox"
          :fixed="options3.fixed"
          @realTime="realTime3"
        >
        </vueCropper>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogStatus.isCropper1 = false">取消</el-button>
          <el-button type="" @click="refreshCrop">重置</el-button>
          <el-button type="primary" @click="finishCropCover3"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>

  <!-- 第三页，课程章节 -->
  <div v-show="thirdPage">
    <el-card class="p-2">
      <el-form
        :model="queryInfo"
        ref="queryFormRef"
        label-position="left"
        label-width="68px"
        :inline-message="false"
      >
        <el-form-item label="课程章节">
          <el-button type="primary" @click="handleAddChapter"
            >添加章节</el-button
          >
        </el-form-item>

        <el-form-item>
          <div
            class="chapterItem"
            v-for="(item, index) in courseChapterList"
            :key="item.id"
          >
            <div>第{{ index + 1 }}节{{ "、" }} {{ (item as any).name }}</div>
            <div
              :id="`play`+ index + (item as any).name "
              style="width: 400px; height: 200px"
            ></div>
            <div>
              <el-button type="primary" @click="editChapter((item as any).id)"
                >修改章节</el-button
              >
              <el-button type="primary" @click="forward(item)" v-if="index > 0"
                >前移</el-button
              >
              <el-button
                type="primary"
                @click="back(item)"
                v-if="index < courseChapterList.length - 1"
                >后移</el-button
              >
              <el-button type="danger" @click="delChapter((item as any).id)"
                >删除</el-button
              >
            </div>
          </div>
        </el-form-item>
        <el-form-item label="">
          <el-button type="success" @click="lastPage">
            <el-icon class="el-icon--left"><ArrowLeft /></el-icon>上一步
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 章节详情 -->
      <el-dialog
        v-model="dialogStatus.addchapter"
        :title="dialogStatus.title"
        width="40%"
        @close="closeDialog"
      >
        <el-form
          :model="queryInfo"
          ref="queryFormRef"
          label-position="left"
          label-width="90px"
        >
          <el-form-item label="章节名称">
            <el-input v-model="addChapter.name" placeholder="请输入章节名" />
          </el-form-item>
          <el-form-item label="是否可评论">
            <el-radio-group v-model="addChapter.allowComment" class="ml-4">
              <el-radio :label="true" size="large">允许</el-radio>
              <el-radio :label="false" size="large">不允许</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="章节排序">
            <el-input-number
              :disabled="true"
              v-model="addChapter.orderNum"
              :min="1"
              :max="1000"
            />
          </el-form-item>
          <el-form-item label="资源" v-if="!addChapter.resourceId">
            <el-button type="primary" @click="chooseResource"
              >选择资源</el-button
            >
            <el-button @click="LocalUpload">本地上传</el-button>
          </el-form-item>

          <el-form-item label="资源" v-else>
            <div
              id="myPlayer"
              v-if="isPoolUpload"
              style="width: 30vw; height: 30vh"
            >
              11
            </div>
            <div id="myPlayer" v-else style="width: 30vw; height: 30vh">22</div>
            <el-button type="primary" @click="chooseResource">
              资源库更换
            </el-button>

            <el-button type="primary" @click="LocalUpload">
              本地更换
            </el-button>
          </el-form-item>

          <el-form-item label="章节详情">
            <el-input
              v-model="addChapter.description"
              placeholder="请输入"
              clearable
              type="textarea"
              :autosize="{ minRows: 8, maxRows: 10 }"
            />
          </el-form-item>

          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="finishAddChapter"> 确认 </el-button>
        </el-form>
      </el-dialog>

      <!-- 资源池dialog -->
      <el-dialog
        v-model="dialogStatus.choseResource"
        title="选择资源"
        width="60%"
        center
      >
        <el-form
          :model="queryResource"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="资源名称" prop="name">
            <el-input
              v-model="queryResource.name"
              placeholder="请输入课程名称"
              clearable
            />
          </el-form-item>

          <el-form-item label="类型" prop="resourceType">
            <el-select
              v-model="queryResource.resourceType"
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in selectArr.typeArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="资源范围" prop="age">
            <el-select v-model="resourceRegion" clearable placeholder="请选择">
              <el-option
                v-for="item in selectArr.resourceRegionArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-table :data="resourceList">
          <el-table-column
            label="资源名称"
            align="center"
            prop="name"
            v-if="true"
          />

          <el-table-column label="资源类型" align="center" prop="resourceType">
          </el-table-column>

          <el-table-column label="上传状态" prop="resourceStatus">
            <template #default="{ row }">
              <el-tag :type="statusType(row.resourceStatus)">{{
                row.resourceStatus
              }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="上传者" align="center" prop="createBy" />

          <el-table-column label="添加时间" align="center" prop="createTime" />
          <el-table-column label="资源备注信息" align="center" prop="remark" />

          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-button link type="primary" @click="chose(scope.row)"
                >选择资源</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryResource.pageNum"
          v-model:limit="queryResource.pageSize"
          @pagination="getResourceList"
        />
      </el-dialog>
      <!-- 从本地新增章节 -->
      <el-dialog
        v-model="dialogStatus.localUpload"
        title="本地上传"
        width="38%"
        center
        :show-close="false"
        :close-on-click-modal="false"
        @close="closeUploadDialog"
      >
        <el-form
          :model="uploadQuery"
          ref="dialogFormRef"
          :inline="true"
          label-width="100px"
          class="dialogForm"
        >
          <el-form-item label="资源名称" prop="name">
            <el-input
              v-model="uploadQuery.name"
              placeholder="请输入名称"
              clearable
              @keyup.enter="handleQuery"
              style="width: 220px"
            />
          </el-form-item>

          <el-form-item label="资源类型" prop="status">
            <el-radio-group v-model="uploadQuery.resourceType">
              <el-radio label="1">视频</el-radio>
              <el-radio label="2">音频</el-radio>
              <el-radio label="3">文档</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="资源文件" prop="type">
            <!-- 查看详情展示 -->
            <!-- <div id="myPlayer" style="width: 400px; height: 200px"></div> -->
            <el-upload class="upload-demo" :before-upload="beforeUpload">
              <el-button type="primary">选择文件</el-button>
              <template #tip>
                <div class="el-upload__tip">
                  {{ uploadQuery.fileName }}
                </div>
              </template>
            </el-upload>
          </el-form-item>

          <el-form-item label="备注信息" prop="remark">
            <el-input
              v-model="uploadQuery.remark"
              :autosize="{ minRows: 3, maxRows: 4 }"
              type="textarea"
              placeholder="Please input"
              style="width: 400px"
            />
          </el-form-item>
          <el-form-item class="dialogFooter">
            <el-button type="primary" icon="Search" @click="uploadSubmit"
              >提交</el-button
            >
            <el-button icon="Refresh" @click="closeUploadDialog"
              >关闭</el-button
            >
          </el-form-item>
        </el-form>
      </el-dialog>

      <!-- 上传进度 -->
      <el-dialog
        v-model="dialogStatus.isUploading"
        title="上传中"
        width="11%"
        center
        :show-close="false"
        :close-on-click-modal="false"
      >
        <el-progress
          type="circle"
          :percentage="currentLoadedPercent"
          :color="colors"
        />
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ZoomIn } from "@element-plus/icons-vue";

import type {
  UploadFile,
  UploadInstance,
  UploadProps,
  UploadRawFile,
} from "element-plus";
import { genFileId } from "element-plus";
import VueCropper from "vue-cropper/src/vue-cropper.vue";
import to from "await-to-js";
import { GetAgeListBo } from "./types";
import {
  addChapter as addChapterApi,
  addCourse as addCourseApi,
  delChapter as delChapterApi,
  exchange as exchangeApi,
  getAgeList as getAgeListApi,
  getAllCourseResource as getAllCourseResourceApi,
  getChapterDetail as getChapterDetailApi,
  getChapterList as getChapterListApi,
  getCourseDetail as getCourseDetailApi,
  getOssAuth as getOssAuthApi,
  getPlayAuth as getPlayAuthApi,
  getPublicCourseResource as getPublicCourseResourceApi,
  getSceneList as getSceneListApi,
  getSecondScene as getSecondSceneApi,
  getSelfCourseResource as getSelfCourseResourceApi,
  getTagList as getTagListApi,
  getUploadAuth as getUploadAuthApi,
  linkCover as linkCoverApi,
  linkImg as linkImgApi,
  postToOSS as postToOSSApi,
  updataChpater as updataChpaterApi,
  updateCourse as updateCourseApi,
} from "@/service/api/course/creat";

const tips = `
<p>如果未上传课程封面和介绍图片，稍后可以在课程列表中进行编辑。</p>
<p>课程封面一图片最小尺寸：375 x 211</p>
<p>课程封面二图片最小尺寸：156 x 211</p>
<p>课程封面三图片最小尺寸：156 x 156</p>
`;

const fileList = ref([]);
const imageSrc = ref(null);

const handleBeforeUpload: UploadProps["beforeUpload"] = (file) => {
  // imageSrc.value = URL.createObjectURL(file.raw);
  // const file = e.target.files[0];
  // fileItem = file;
  console.log("file:", file);
  // const URL = window.URL || window.webkitURL;
  options1.img = URL.createObjectURL(file.raw);
  console.log("options1.img:", options1.img);
  dialogStatus.value.isCropper1 = true;
};

const selectArr = reactive({
  // 课程类别
  typeArr: [
    {
      value: "1",
      label: "课程",
    },
    {
      value: "2",
      label: "读书",
    },
  ],
  // 孩子年龄列表
  childAgeArr: [],
  // 父母年龄列表
  parentAgeArr: [],
  // 场景列表
  sceneArr: [],
  // 二级分类列表
  categoryList: [],
  // 标签列表
  labelList: [],
  // 资源类型
  resourceRegionArr: [
    {
      value: "0",
      label: "组织私有",
    },
    {
      value: "1",
      label: "公共资源",
    },
    {
      value: "2",
      label: "全部资源",
    },
  ],
});
const checked = ref(false);
const firstPage = ref(true);
const firstPageSaved = ref(false);
const secondPage = ref(false);
const thirdPage = ref(false);
const queryFormRef = ref();
const total = ref(0);
// 当前课程id
const currentCourseId = ref();
// 资源范围
const resourceRegion = ref("2");
// 资源列表
const resourceList = ref([]);
// 课程的章节列表
const courseChapterList = ref([]);
const initDialogStatus = {
  isCropper1: false,
  isCropper2: false,
  isCropper3: false,
  preview: false,
  title: "",
  addchapter: false,
  choseResource: false,
  localUpload: false,
  isUploading: false,
};
const initUploadQuery = {
  id: "",
  name: "",
  fileName: "",
  resourceType: "1",
  remark: "",
  sectionList: [],
  open: null,
};
// 新建课程参数
const initQueryInfo = {
  id: "",
  core: false,
  name: "",
  subtitle: "",
  organizationId: "",
  ownerId: "",
  sceneId: "",
  totalSection: undefined,
  type: "",
  categoryId: "",
  remark: "",
  labelList: [],
  childAgeList: [],
  parentAgeList: [],
  introduction: "",
  cover1: null,
  cover2: null,
  cover3: null,
};
const initGetAgeListBo: GetAgeListBo = {
  type: "1",
};
// 获取资源列表BO
const initQueryResource = {
  name: "",
  resourceStatus: 1,
  resourceType: "",
  remark: "",
  pageSize: 10,
  pageNum: 1,
};
// 新增章节BO
const initAddChapter = {
  // 是否评论
  allowComment: false,
  // 章节排序
  orderNum: "1",
  resourceId: "",
  name: "",
  courseId: "217152695091205",
  description: "",
};
// 交换章节顺序BO
const initExchangeBO = {
  sectionId1: "",
  sectionId2: "",
};
// 获取章节listBO
const initGetChapterList = {
  courseId: "",
};

// 课程绑定图片
const initLinkImgBO = {
  courseId: "",
  ossId: "",
  type: 1,
  orderNum: 0,
};
// 课程绑定封面
const initLinkCoverBO = {
  courseId: "",
  type: 1,
  url: "",
};

const data = reactive({
  queryInfo: {
    ...initQueryInfo,
  },
  getAgeListBo: {
    ...initGetAgeListBo,
  },
  dialogStatus: { ...initDialogStatus },
  addChapter: { ...initAddChapter },
  queryResource: { ...initQueryResource },
  getChapterListBO: { ...initGetChapterList },
  linkImgBO: { ...initLinkImgBO },
  linkCoverBO: { ...initLinkCoverBO },
  exchangeBO: { ...initExchangeBO },
  uploadQuery: { ...initUploadQuery },
  rules: {
    name: [{ required: true, message: "课程标题不能为空", trigger: "blur" }],
    introduction: [
      { required: true, message: "解决问题不能为空", trigger: "blur" },
    ],
    subtitle: [{ required: true, message: "副标题不能为空", trigger: "blur" }],
    childAgeList: [
      { required: true, message: "孩子年龄为必选", trigger: "blur" },
    ],
    type: [{ required: true, message: "类型为必选", trigger: "blur" }],
    totalSection: [
      { required: true, message: "章节数量为必选", trigger: "blur" },
      { type: "number", message: "章节数量必须为数字值", trigger: "blur" },
      {
        type: "number",
        min: 1,
        message: "请至少指定一个章节",
        trigger: "blur",
      },
    ],
    sceneId: [{ required: true, message: "分类为必选", trigger: "blur" }],
    label: [{ required: true, message: "标签为必选", trigger: "blur" }],
  },
});
const {
  queryInfo,
  getAgeListBo,
  dialogStatus,
  addChapter,
  queryResource,
  getChapterListBO,
  linkImgBO,
  linkCoverBO,
  exchangeBO,
  rules,
  uploadQuery,
} = toRefs(data);

// 获取孩子年龄列表、家长年龄列表、所有场景
const getDefaultList = async () => {
  getAgeListBo.value.type = "1";
  const res = await getAgeListApi(getAgeListBo.value);
  selectArr.childAgeArr = res.rows;
  getAgeListBo.value.type = "2";
  const res2 = await getAgeListApi(getAgeListBo.value);
  selectArr.parentAgeArr = res2.rows;
  const res3 = await getSceneListApi();
  selectArr.sceneArr = res3.rows;
};

// 获取二级分类
const getFirstCategoryList = async (id: string) => {
  const res = await getSecondSceneApi(id);
  console.log(res);
  selectArr.categoryList = res.data;
};

// 获取标签
const getCategoryLabelList = async (id: string) => {
  const res = await getTagListApi(id);
  console.log(res);
  selectArr.labelList = res.data;
};

// 选中场景分类时
const handelSceneChange = (id: any) => {
  // 有id为切换，无id为删除
  if (id) {
    // 获取一级分类
    getFirstCategoryList(id);
  }

  // 清空一级分类和标签
  selectArr.categoryList = [];
  queryInfo.value.categoryId = "";
  selectArr.labelList = [];
  queryInfo.value.labelList = [];

  firstPageSaved.value = false;
};

// 选中一级分类时
const handelFirstCategoryChange = (id: any) => {
  // 有id为切换，无id为删除
  if (id) {
    getCategoryLabelList(id);
  }

  // 清空标签
  selectArr.labelList = [];
  queryInfo.value.labelList = [];

  firstPageSaved.value = false;
};

// 选择标签
const tagChange = (label: any) => {
  console.log(label);

  if (label.checked) {
    // 如果已经选择
    label.checked = false;
    queryInfo.value.labelList = queryInfo.value.labelList.filter(
      (item: any) => {
        return item !== label.id;
      }
    );
    console.log(queryInfo.value.labelList);
  } else {
    // 如果未选择
    label.checked = !checked.value;
    (queryInfo as any).value.labelList!.push(label.id);
  }
  firstPageSaved.value = false;

  // console.log(status);
  console.log(label, queryInfo.value.labelList);
};

const isAddedCourse = ref(false);

// 保存课程按钮
const saveCourse = () => {
  queryFormRef.value.validate(async (vilid: boolean) => {
    if (vilid) {
      // 新增
      if (queryInfo.value.id === "") {
        // 如果验证通过
        const [err, res] = await to(addCourseApi(queryInfo.value));
        if (!err) {
          firstPageSaved.value = true;
          ElMessage({
            message: "新增成功",
            type: "success",
          });
          // 标记添加过课程了
          isAddedCourse.value = true;
          // 实体有id表示已经提交过了
          queryInfo.value.id = res.data;
          // 添加章节
          addChapter.value.courseId = res.data;
          // 获取章节
          getChapterListBO.value.courseId = res.data;
          // 课程绑定图片
          linkImgBO.value.courseId = res.data;
          // 课程绑定封面
          linkCoverBO.value.courseId = res.data;
          console.log(addChapter.value, res);
        }
      }
      // 修改
      else {
        const [err] = await to(updateCourseApi(queryInfo.value));
        if (!err) {
          firstPageSaved.value = true;
          ElMessage({
            message: "修改成功",
            type: "success",
          });
        }
      }
    }
  });
};

const handleResetCourse = async () => {
  if (firstPageSaved.value == false) {
    // 询问用户是否要保存课程
    const [err, confirm] = await to<string, string>(
      ElMessageBox.confirm("课程还未保存，是否确定要重置？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
    );
    if (err === "cancel") {
      ElMessage({
        type: "info",
        message: "取消重置",
      });
    } else if (confirm === "confirm") {
      // 未保存过
      if (queryInfo.value.id === "") {
        // 清空
        queryInfo.value = Object.assign({}, initQueryInfo);
        selectArr.labelList = [];
        queryInfo.value.labelList = [];

        firstPageSaved.value = false;
      }
      // 保存过
      else {
        // 刷新
        const [err, res] = await to(getCourseDetailApi(queryInfo.value.id));
        if (!err) {
          queryInfo.value = res.data;

          // 获取一级分类列表
          await getFirstCategoryList(res.data.sceneId);
          // 获取一级分类id
          if (res.data.category) {
            queryInfo.value.categoryId = res.data.category.id;
            // 获取一级分类下所有标签
            await getCategoryLabelList(res.data.category.id);
          }
          // 默认高亮已有labels
          // 因为返回detail里面没有labelList字段，直接手动添加
          queryInfo.value.labelList = [];
          if (res.data.labels) {
            res.data.labels.map((item: any) => {
              (queryInfo as any).value.labelList!.push(item.id);
            });
          }
          selectArr.labelList.map((item: any) => {
            if ((queryInfo as any).value.labelList?.includes(item.id)) {
              item.checked = !checked.value;
            }
          });
          ElMessage({
            type: "success",
            message: "重置成功",
          });
          firstPageSaved.value = true;
        }
      }
    }
  }
};

onMounted(() => {
  getDefaultList();
});

// 上传图片页面

interface Options {
  img: string | ArrayBuffer | null; // 裁剪图片的地址
  info: true; // 裁剪框的大小信息
  outputSize: number; // 裁剪生成图片的质量 [1至0.1]
  outputType: "jpeg"; // 裁剪生成图片的格式
  canScale: boolean; // 图片是否允许滚轮缩放
  autoCrop: boolean; // 是否默认生成截图框
  autoCropWidth: number; // 默认生成截图框宽度
  autoCropHeight: number; // 默认生成截图框高度
  fixedBox: boolean; // 固定截图框大小 不允许改变
  fixed: boolean; // 是否开启截图框宽高固定比例
  fixedNumber?: Array<number>; // 截图框的宽高比例  需要配合centerBox一起使用才能生效
  full: boolean; // 是否输出原图比例的截图
  canMoveBox: boolean; // 截图框能否拖动
  original: boolean; // 上传图片按照原始比例渲染
  centerBox: boolean; // 截图框是否被限制在图片里面
  infoTrue: boolean; // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
  enlarge: number;
}
// 封面1
const options1: Options = reactive({
  img: "", // 需要剪裁的图片
  autoCrop: true, // 是否默认生成截图框
  autoCropWidth: 370, // 默认生成截图框的宽度
  autoCropHeight: 249, // 默认生成截图框的长度
  fixedBox: true, // 是否固定截图框的大小 不允许改变
  info: true, // 裁剪框的大小信息
  outputSize: 1, // 裁剪生成图片的质量 [1至0.1]
  outputType: "jpeg", // 裁剪生成图片的格式
  canScale: true, // 图片是否允许滚轮缩放
  fixed: true, // 是否开启截图框宽高固定比例
  fixedNumber: [370, 249], // 截图框的宽高比例 需要配合centerBox一起使用才能生效
  full: false, // 是否输出原图比例的截图
  canMoveBox: true, // 截图框能否拖动
  original: false, // 上传图片按照原始比例渲染
  centerBox: false, // 截图框是否被限制在图片里面
  infoTrue: false, // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
  enlarge: 2,
});
// 封面2
const options2: Options = reactive({
  img: "", // 需要剪裁的图片
  autoCrop: true, // 是否默认生成截图框
  autoCropWidth: 170, // 默认生成截图框的宽度
  autoCropHeight: 230, // 默认生成截图框的长度
  fixedBox: true, // 是否固定截图框的大小 不允许改变
  info: true, // 裁剪框的大小信息
  outputSize: 1, // 裁剪生成图片的质量 [1至0.1]
  outputType: "jpeg", // 裁剪生成图片的格式
  canScale: true, // 图片是否允许滚轮缩放
  fixed: true, // 是否开启截图框宽高固定比例
  fixedNumber: [85, 115], // 截图框的宽高比例 需要配合centerBox一起使用才能生效
  full: false, // 是否输出原图比例的截图
  canMoveBox: true, // 截图框能否拖动
  original: false, // 上传图片按照原始比例渲染
  centerBox: false, // 截图框是否被限制在图片里面
  infoTrue: false, // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
  enlarge: 2,
});
// 封面3
const options3: Options = reactive({
  img: "", // 需要剪裁的图片
  autoCrop: true, // 是否默认生成截图框
  autoCropWidth: 200, // 默认生成截图框的宽度
  autoCropHeight: 200, // 默认生成截图框的长度
  fixedBox: true, // 是否固定截图框的大小 不允许改变
  info: true, // 裁剪框的大小信息
  outputSize: 1, // 裁剪生成图片的质量 [1至0.1]
  outputType: "jpeg", // 裁剪生成图片的格式
  canScale: true, // 图片是否允许滚轮缩放
  fixed: true, // 是否开启截图框宽高固定比例
  fixedNumber: [1, 1], // 截图框的宽高比例 需要配合centerBox一起使用才能生效
  full: false, // 是否输出原图比例的截图
  canMoveBox: true, // 截图框能否拖动
  original: false, // 上传图片按照原始比例渲染
  centerBox: false, // 截图框是否被限制在图片里面
  infoTrue: false, // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
  enlarge: 2,
});
// 封面1
const previews1: any = ref({});
// 封面2
const previews2: any = ref({});
// 封面3
const previews3: any = ref({});

let fileItem = reactive({});
const cropperRef: any = ref({});
const isValue = ref();
const isNext = ref(false);

// 选择的原始封面文件
const originalCoverFile1 = ref({});
const originalCoverFile2 = ref({});
const originalCoverFile3 = ref({});

// 封面图片文件列表
const coverFile1 = ref();
const coverFile2 = ref();
const coverFile3 = ref();

// 封面图片是否选中
const isSelectedCover1 = ref(false); // 是否选了图片
const isSelectedCover2 = ref(false);
const isSelectedCover3 = ref(false);

// 封面图片是否改变过
const isChangedCover1 = ref(false);
const isChangedCover2 = ref(false);
const isChangedCover3 = ref(false);

// 是否上传成功
const isUploadedCover1 = ref(false); // 上传成功
const isUploadedCover2 = ref(false);
const isUploadedCover3 = ref(false);

const initCoverParams = {
  OSSAccessKeyId: "",
  callback: "",
  dir: "",
  expire: "",
  host: "",
  policy: "",
  service: "",
  signature: "",
  file: "",
  key: "",
};
const SecondData = reactive({
  coverParams: { ...initCoverParams },
});
const { coverParams } = toRefs(SecondData);
// 触发点击事件
const uploadClick1 = () => {
  isValue.value = "";
  document.getElementById("fileBtn1")?.click();
};
const uploadClick2 = () => {
  isValue.value = "";
  document.getElementById("fileBtn2")?.click();
};
const uploadClick3 = () => {
  isValue.value = "";
  document.getElementById("fileBtn3")?.click();
};
// const introduceItem_uploadClick1 = () => {
//   isValue.value = "";
//   document.getElementById("introduceItem_fileBtn1")?.click();
// };

// const introduceItem_uploadClick2 = () => {
//   isValue.value = "";
//   document.getElementById("introduceItem_fileBtn2")?.click();
// };

// const introduceItem_uploadClick3 = () => {
//   isValue.value = "";
//   document.getElementById("introduceItem_fileBtn3")?.click();
// };

// const introduceItem_uploadClick4 = () => {
//   isValue.value = "";
//   document.getElementById("introduceItem_fileBtn4")?.click();
// };

// 截图调整重置
const refreshCrop = () => {
  cropperRef.value.refresh();
};
// 点击截图保存按钮
const finishCropCover1 = () => {
  // cropperRef.value.getCropData((data: any) => {
  //   // console.log("获取截图的 base64 数据:", data);
  //   // data为base64图片，供接口使用
  // });
  cropperRef.value.getCropBlob((data: any) => {
    console.log("获取截图的 blob 数据:", data);
    // 下面是将blob转为formData
    let formData = new FormData();
    formData.append("file", data, new Date().getTime() + ".jpg");
    console.log("formData:", formData);
    // 下面是将blob转换为file
    data.lastModifiedDate = new Date(); // 文件最后的修改日期
    let file = new File([data], originalCoverFile1.value.name, {
      type: data.type,
      lastModified: Date.now(),
    });
    console.log("file:", file);
    console.log("fileItem:", JSON.parse(JSON.stringify(fileItem)));
    // 获取文件名
    // getOssAuthBO.originalFileName = (file as any).name;
    coverFile1.value = file;
  });
  // 设置文件选择状态
  isSelectedCover1.value = true;
  isUploadedCover1.value = false;

  dialogStatus.value.isCropper1 = false;
};

const finishCropCover2 = () => {
  // cropperRef.value.getCropData((data: any) => {
  //   // console.log("获取截图的 base64 数据:", data);
  //   // data为base64图片，供接口使用
  // });
  cropperRef.value.getCropBlob((data: any) => {
    console.log("获取截图的 blob 数据:", data);
    // 下面是将blob转为formData
    let formData = new FormData();
    formData.append("file", data, new Date().getTime() + ".jpg");
    console.log("formData:", formData);
    // 下面是将blob转换为file
    data.lastModifiedDate = new Date(); // 文件最后的修改日期
    let file = new File([data], (fileItem as any).name, {
      type: data.type,
      lastModified: Date.now(),
    });
    console.log("file:");
    console.log("fileItem:", JSON.parse(JSON.stringify(fileItem)));
    // 获取文件后缀
    // getOssAuthBO.originalFileName = (file as any).name;
    coverFile2.value = file;
  });

  isSelectedCover2.value = true;
  isUploadedCover2.value = false;

  dialogStatus.value.isCropper2 = false;
};

const finishCropCover3 = () => {
  // cropperRef.value.getCropData((data: any) => {
  //   // console.log("获取截图的 base64 数据:", data);
  //   // data为base64图片，供接口使用
  // });
  cropperRef.value.getCropBlob((data: any) => {
    console.log("获取截图的 blob 数据:", data);
    // 下面是将blob转为formData
    let formData = new FormData();
    formData.append("file", data, new Date().getTime() + ".jpg");
    console.log("formData:", formData);
    // 下面是将blob转换为file
    data.lastModifiedDate = new Date(); // 文件最后的修改日期
    let file = new File([data], (fileItem as any).name, {
      type: data.type,
      lastModified: Date.now(),
    });
    console.log("file:", file);
    console.log("fileItem:", JSON.parse(JSON.stringify(fileItem)));
    // getOssAuthBO.originalFileName = (file as any).name;
    coverFile3.value = file;
  });

  isSelectedCover3.value = true;
  isUploadedCover3.value = false;

  dialogStatus.value.isCropper3 = false;
};

// 裁剪之后的数据

const realTime1 = (data: any) => {
  // console.log("realTime:", data);
  previews1.value = data;
  console.log(previews1.value);
};

const realTime2 = (data: any) => {
  // console.log("realTime:", data);
  previews2.value = data;
  console.log(previews1.value);
};

const realTime3 = (data: any) => {
  // console.log("realTime:", data);
  previews3.value = data;
  console.log(previews1.value);
};

// const realTime4 = (data: any) => {
//   // console.log("realTime:", data);
//   introduceItem_previews1.value = data;
//   console.log(previews1.value);
// };

// const realTime5 = (data: any) => {
//   // console.log("realTime:", data);
//   introduceItem_previews2.value = data;
//   console.log(previews1.value);
// };

// const realTime6 = (data: any) => {
//   // console.log("realTime:", data);
//   introduceItem_previews3.value = data;
//   console.log(previews1.value);
// };

// const realTime7 = (data: any) => {
//   // console.log("realTime:", data);
//   introduceItem_previews4.value = data;
//   console.log(previews1.value);
// };

const dialogImageUrl = ref("");
const disabled = ref(false);
const upload4 = ref<UploadInstance>();
const upload5 = ref<UploadInstance>();
const upload6 = ref<UploadInstance>();
const upload7 = ref<UploadInstance>();

const courseStructure = ref();
const courseIntroduction = ref();
const courseTips = ref();
const courseTeam = ref();

const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!;
  dialogStatus.value.preview = true;
};

// 选择文件改变时调用
const handleChange4 = (uploadFile: any) => {
  console.log(uploadFile);
  courseStructure.value = uploadFile;
  isSelected4.value = true;
  isUploaded4.value = false;
};
// 选择文件改变时调用
const handleChange5 = (uploadFile: any) => {
  console.log(uploadFile);
  courseIntroduction.value = uploadFile;
  isSelected5.value = true;
  isUploaded5.value = false;
};
// 选择文件改变时调用
const handleChange6 = (uploadFile: any) => {
  console.log(uploadFile);
  courseTips.value = uploadFile;
  isSelected6.value = true;
  isUploaded6.value = false;
};
// 选择文件改变时调用
const handleChange7 = (uploadFile: any) => {
  console.log(uploadFile);
  courseTeam.value = uploadFile;
  isSelected7.value = true;
  isUploaded7.value = false;
};

// 超出一个文件时调用
const handleExceed4: UploadProps["onExceed"] = (files) => {
  // 手动加入一个文件
  console.log(courseStructure.value);
  upload4.value!.handleStart(courseStructure.value);
  // 清除文件
  upload4.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload4.value!.handleStart(file);
};

const handleExceed5: UploadProps["onExceed"] = (files) => {
  // 手动加入一个文件
  console.log(courseIntroduction.value);
  upload5.value!.handleStart(courseIntroduction.value);
  // 清除文件
  upload5.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload5.value!.handleStart(file);
};

const handleExceed6: UploadProps["onExceed"] = (files) => {
  // 手动加入一个文件
  console.log(courseTips.value);
  upload6.value!.handleStart(courseTips.value);
  // 清除文件
  upload6.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload6.value!.handleStart(file);
};

const handleExceed7: UploadProps["onExceed"] = (files) => {
  // 手动加入一个文件
  console.log(courseTeam.value);
  upload7.value!.handleStart(courseTeam.value);
  // 清除文件
  upload7.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload7.value!.handleStart(file);
};

// 获取凭证的BO
const getOssAuthBO = reactive({
  originalFileName: "",
});
// 获取凭证
const getOssAuth = async (originalFilename: string) => {
  getOssAuthBO.originalFileName = originalFilename;
  const res = await getOssAuthApi(getOssAuthBO);
  (coverParams.value as any) = res;
  console.log(res);
};

// 上传封面1
const handleUploadCover1 = async () => {
  const [err] = await to(getOssAuth(originalCoverFile1.value.name));

  if (!err) {
    const formData = new FormData();
    formData.append("key", coverParams.value.key);
    formData.append("OSSAccessKeyId", coverParams.value.OSSAccessKeyId);
    formData.append("policy", coverParams.value.policy);
    formData.append("signature", coverParams.value.signature);
    formData.append("x:cover", "cover1");
    formData.append("success_action_status", "200"); // 上传成功返回的状态码，不设置则是204
    formData.append("callback", coverParams.value.callback);
    formData.append("file", coverFile1.value); // 一定在最后

    console.log(formData);

    const res = await postToOSSApi(formData);
    console.log(res);
    // 是否上传成功
    if (res.status === 200) {
      ElMessage({
        type: "success",
        message: "上传成功",
      });

      // 是否拿到上传的图片的id
      if (res.data.code === 200) {
        linkCoverBO.value.url = res.data.data.url;
        linkCoverBO.value.type = 1;
        const response = await linkCover();
        if (response) {
          isUploadedCover1.value = true;
          ElMessage({
            type: "success",
            message: "封面和课程绑定成功",
          });
          isNext.value = true;
        } else {
          ElMessage({
            type: "error",
            message: "封面和课程绑定失败",
          });
        }
      } else {
        ElMessage({
          type: "error",
          message: "无法获取上传文件的链接",
        });
      }
    } else {
      ElMessage({
        type: "error",
        message: "上传失败，请联系管理员",
      });
    }
  }
};

// 上传封面2
const handleUploadCover2 = async () => {
  await getOssAuth(originalCoverFile2.value.name);

  const formData = new FormData();
  formData.append("key", coverParams.value.key);
  formData.append("OSSAccessKeyId", coverParams.value.OSSAccessKeyId);
  formData.append("policy", coverParams.value.policy);
  formData.append("signature", coverParams.value.signature);
  formData.append("x:cover", "cover2");
  formData.append("success_action_status", "200"); // 上传成功返回的状态码，不设置则是204
  formData.append("callback", coverParams.value.callback);
  formData.append("file", coverFile2.value); // 一定在最后

  console.log(formData);
  const res = await postToOSSApi(formData);
  console.log(res);
  if (res.status === 200) {
    ElMessage({
      type: "success",
      message: "上传成功",
    });
    if (res.data.code === 200) {
      linkCoverBO.value.url = res.data.data.url;
      linkCoverBO.value.type = 2;
      const response = await linkCover();
      if (response) {
        isNext.value = true;
        isUploadedCover2.value = true;
        ElMessage({
          type: "success",
          message: "封面和课程绑定成功",
        });
      } else {
        ElMessage({
          type: "error",
          message: "封面和课程绑定失败",
        });
      }
    } else {
      ElMessage({
        type: "error",
        message: "无法获取图片链接",
      });
    }
  } else {
    ElMessage({
      type: "error",
      message: "上传失败,请联系管理员。",
    });
  }
};

// 上传封面3
const handleUploadCover3 = async () => {
  await getOssAuth(originalCoverFile3.value.name);

  const formData = new FormData();
  formData.append("key", coverParams.value.key);
  formData.append("OSSAccessKeyId", coverParams.value.OSSAccessKeyId);
  formData.append("policy", coverParams.value.policy);
  formData.append("signature", coverParams.value.signature);
  formData.append("x:cover", "cover3");
  formData.append("success_action_status", "200"); // 上传成功返回的状态码，不设置则是204
  formData.append("callback", coverParams.value.callback);
  formData.append("file", coverFile3.value); // 一定在最后

  console.log(formData);
  const res = await postToOSSApi(formData);
  console.log(res);
  if (res.status === 200) {
    ElMessage({
      type: "success",
      message: "上传成功",
    });
    if (res.data.code === 200) {
      linkCoverBO.value.url = res.data.data.url;
      linkCoverBO.value.type = 3;
      const response = await linkCover();
      if (response) {
        isNext.value = true;
        isUploadedCover3.value = true;
        ElMessage({
          type: "success",
          message: "封面和课程绑定成功",
        });
      } else {
        ElMessage({
          type: "error",
          message: "封面和课程绑定失败",
        });
      }
    } else {
      ElMessage({
        type: "error",
        message: "无法获取图片链接",
      });
    }
  } else {
    ElMessage({
      type: "error",
      message: "上传失败,请联系管理员。",
    });
  }
};

// 是否选择文件
const isSelected4 = ref(false);
const isSelected5 = ref(false);
const isSelected6 = ref(false);
const isSelected7 = ref(false);

// 是否上传完毕
const isUploaded4 = ref(false);
const isUploaded5 = ref(false);
const isUploaded6 = ref(false);
const isUploaded7 = ref(false);

// 结构图片上传
const handleUpload4 = async () => {
  await getOssAuth(courseStructure.value.name);
  const formData = new FormData();
  formData.append("key", coverParams.value.key);
  formData.append("OSSAccessKeyId", coverParams.value.OSSAccessKeyId);
  formData.append("policy", coverParams.value.policy);
  formData.append("signature", coverParams.value.signature);
  formData.append("x:structure", "structure");
  formData.append("success_action_status", "200"); // 上传成功返回的状态码，不设置则是204
  formData.append("callback", coverParams.value.callback);
  formData.append("file", courseStructure.value.raw); // 一定在最后
  console.log(formData);
  const res = await postToOSSApi(formData);
  console.log(res);
  if (res.status === 200) {
    ElMessage({
      type: "success",
      message: "图片上传成功",
    });

    if (res.data.code === 200) {
      linkImgBO.value.ossId = res.data.data.id;
      linkImgBO.value.type = 1;
      // console.log(linkImgBO.value);
      const response = await linkImg();
      if (response) {
        isNext.value = true;
        isUploaded4.value = true;

        ElMessage({
          type: "success",
          message: "图片和课程绑定成功",
        });
      } else {
        ElMessage({
          type: "success",
          message: "图片和课程绑定失败",
        });
      }
    } else {
      ElMessage({
        type: "error",
        message: "无法获取图片id",
      });
    }
  } else {
    ElMessage({
      type: "error",
      message: "上传失败，请联系管理员。",
    });
  }
};

// 介绍图片上传
const handleUpload5 = async () => {
  await getOssAuth(courseIntroduction.value.name);
  const formData = new FormData();
  formData.append("key", coverParams.value.key);
  formData.append("OSSAccessKeyId", coverParams.value.OSSAccessKeyId);
  formData.append("policy", coverParams.value.policy);
  formData.append("signature", coverParams.value.signature);
  formData.append("x:structure", "structure");
  formData.append("success_action_status", "200"); // 上传成功返回的状态码，不设置则是204
  formData.append("callback", coverParams.value.callback);
  formData.append("file", courseIntroduction.value.raw); // 一定在最后
  console.log(formData);
  const res = await postToOSSApi(formData);
  console.log(res);
  if (res.status === 200) {
    ElMessage({
      type: "success",
      message: "图片上传成功",
    });
    if (res.data.code === 200) {
      linkImgBO.value.ossId = res.data.data.id;
      linkImgBO.value.type = 2;
      const response = await linkImg();
      if (response) {
        ElMessage({
          type: "success",
          message: "图片和课程绑定成功",
        });
        isNext.value = true;
        isUploaded5.value = true;
      } else {
        ElMessage({
          type: "error",
          message: "图片和课程绑定失败",
        });
      }
    } else {
      ElMessage({
        type: "error",
        message: "获取图片信息失败",
      });
    }
  } else {
    ElMessage({
      type: "error",
      message: "上传失败,请联系管理员。",
    });
  }
};

// 课程推荐上传
const handleUpload6 = async () => {
  await getOssAuth(courseTips.value.name);
  const formData = new FormData();
  formData.append("key", coverParams.value.key);
  formData.append("OSSAccessKeyId", coverParams.value.OSSAccessKeyId);
  formData.append("policy", coverParams.value.policy);
  formData.append("signature", coverParams.value.signature);
  formData.append("x:structure", "structure");
  formData.append("success_action_status", "200"); // 上传成功返回的状态码，不设置则是204
  formData.append("callback", coverParams.value.callback);
  formData.append("file", courseTips.value.raw); // 一定在最后
  console.log(formData);
  const res = await postToOSSApi(formData);
  console.log(res);
  if (res.status === 200) {
    ElMessage({
      type: "success",
      message: "图片上传成功",
    });
    if (res.data.code === 200) {
      linkImgBO.value.ossId = res.data.data.id;
      linkImgBO.value.type = 3;
      const response = await linkImg();
      if (response) {
        isNext.value = true;
        isUploaded6.value = true;
        ElMessage({
          type: "success",
          message: "图片和课程绑定成功",
        });
      } else {
        ElMessage({
          type: "error",
          message: "图片和课程绑定失败",
        });
      }
    } else {
      ElMessage({
        type: "error",
        message: "获取图片信息失败",
      });
    }
  } else {
    ElMessage({
      type: "error",
      message: "上传失败,请联系管理员。",
    });
  }
};

// 课程讲师团队上传
const handleUpload7 = async () => {
  await getOssAuth(courseTeam.value.name);
  const formData = new FormData();
  formData.append("key", coverParams.value.key);
  formData.append("OSSAccessKeyId", coverParams.value.OSSAccessKeyId);
  formData.append("policy", coverParams.value.policy);
  formData.append("signature", coverParams.value.signature);
  formData.append("x:structure", "structure");
  formData.append("success_action_status", "200"); // 上传成功返回的状态码，不设置则是204
  formData.append("callback", coverParams.value.callback);
  formData.append("file", courseTeam.value.raw); // 一定在最后
  console.log(formData);
  const res = await postToOSSApi(formData);
  console.log(res);
  if (res.status === 200) {
    ElMessage({
      type: "success",
      message: "图片上传成功",
    });
    if (res.data.code === 200) {
      linkImgBO.value.ossId = res.data.data.id;
      linkImgBO.value.type = 4;
      const response = await linkImg();
      if (response) {
        isNext.value = true;
        isUploaded7.value = true;

        ElMessage({
          type: "success",
          message: "图片和课程绑定成功",
        });
      } else {
        ElMessage({
          type: "error",
          message: "图片和课程绑定失败",
        });
      }
    } else {
      ElMessage({
        type: "error",
        message: "获取图片信息失败",
      });
    }
  } else {
    ElMessage({
      type: "error",
      message: "上传失败,请联系管理员。",
    });
  }
};

// 绑定课程跟介绍图片
const linkImg = async (): Promise<boolean> => {
  const [err, res] = await to(linkImgApi(linkImgBO.value));
  if (!err) {
    console.log(res);
    return true;
  }
  return false;
};

// 课程绑定封面
const linkCover = async (): Promise<boolean> => {
  const [err, res] = await to(linkCoverApi(linkCoverBO.value));
  if (!err) {
    console.log(res);
    return true;
  }
  return false;
};

// 新增章节按钮
const handleAddChapter = () => {
  dialogStatus.value.addchapter = true;
  dialogStatus.value.title = "新增章节";
};

// 选择资源按钮
const chooseResource = async () => {
  dialogStatus.value.choseResource = true;
  await getResourceList();
};

// 初始化上传
const initupload = () => {
  return new AliyunUpload.Vod({
    //userID，必填，您可以使用阿里云账号访问账号中心（https://account.console.aliyun.com/），即可查看账号ID
    userId: "1424582593277949",
    //上传到视频点播的地域，默认值为'cn-shanghai'，
    //eu-central-1，ap-southeast-1
    region: "",
    //分片大小默认1 MB，不能小于100 KB（100*1024）
    partSize: 1048576,
    //并行上传分片个数，默认5
    parallel: 5,
    //网络原因失败时，重新上传次数，默认为3
    retryCount: 3,
    //网络原因失败时，重新上传间隔时间，默认为2秒
    retryDuration: 2,
    //开始上传
    // onUploadstarted: (uploadInfo) => {},
    // //文件上传成功
    // onUploadSucceed: function (uploadInfo) {},
    // //文件上传失败
    // onUploadFailed: function (uploadInfo, code, message) {},
    // //文件上传进度，单位：字节
    // onUploadProgress: function (uploadInfo, totalSize, loadedPercent) {},
    // //上传凭证或STS token超时
    // onUploadTokenExpired: function (uploadInfo) {},
    // //全部文件上传结束
    // onUploadEnd: function (uploadInfo) {},
  });
};

// 保存上传文件
const videoFile = ref();
const resKey = ref();
const isPoolUpload = ref(false);
// 上传之前获得文件
const beforeUpload = async (file: any) => {
  // 获取资源
  videoFile.value = file;
  // 获取文件名
  uploadQuery.value.fileName = file.name;
  // 阻断element组件自定义的行为
  return false;
};

// 百分比
const currentLoadedPercent = ref();
// 暂存播放器
const vodPlayer = ref();

// 上传本地资源
const send = async () => {
  // 是否是本地上传
  isPoolUpload.value = false;
  // 百分比dialog
  dialogStatus.value.isUploading = true;
  // 获取上传实例
  const uploader = initupload();
  // 添加上传文件
  uploader.addFile(videoFile.value);
  // 获取凭证并设置
  uploader.options.onUploadstarted = async (uploaderInfo: any) => {
    const [err, res] = await to(getUploadAuthApi(uploadQuery.value));
    if (!err) {
      resKey.value = res.data;
      addChapter.value.resourceId = resKey.value.extraInfo.id;
      uploader.setUploadAuthAndAddress(
        uploaderInfo,
        resKey.value.uploadAuth,
        resKey.value.uploadAddress,
        resKey.value.vid
      );
    } else {
      throw err;
    }
  };
  // 开始上传
  await uploader.startUpload();

  // 上传进度
  uploader.options.onUploadProgress = async (
    uploadInfo: any,
    totalSize: any,
    loadedPercent: any
  ) => {
    currentLoadedPercent.value = loadedPercent * 100;
    console.log(currentLoadedPercent.value === 100);

    if (currentLoadedPercent.value >= 100) {
      const vid: string = uploadInfo.videoId;

      const [err, res2] = await to(getPlayAuthApi(vid));
      if (!err) {
        const playAuth = res2.data.playAuth;
        nextTick(() => {
          if (vodPlayer.value) {
            console.log(vodPlayer.value);

            // 销毁之前已有的视频
            vodPlayer.value.dispose();
            vodPlayer.value = new Aliplayer({
              id: "myPlayer",
              width: "100%",
              vid: vid, //必选参数。音视频ID。示例：1e067a2831b641db90d570b6480f****。
              playauth: playAuth, //必选参数。音视频播放凭证。
              autoplay: false,
              preload: false,
            });
          } else {
            console.log(vodPlayer.value);

            vodPlayer.value = new Aliplayer({
              id: "myPlayer",
              width: "100%",
              vid: vid, //必选参数。音视频ID。示例：1e067a2831b641db90d570b6480f****。
              playauth: playAuth, //必选参数。音视频播放凭证。
              autoplay: false,
              preload: false,
            });
          }
        });
        dialogStatus.value.localUpload = false;
        uploadQuery.value = Object.assign({}, initUploadQuery);
        currentLoadedPercent.value = 0;
        dialogStatus.value.isUploading = false;
      }
    }
  };
};

// 本地上传按钮
const LocalUpload = async () => {
  dialogStatus.value.localUpload = true;
};

// 确定上传按钮
const uploadSubmit = async () => {
  const [err, res] = await to(send());
  if (!err) {
    // // 在这里拿回调
    // console.log(res);
    // setTimeout(async () => {
    //   ElMessage({
    //     message: "新增成功",
    //     type: "success",
    //   });
    //   dialogStatus.value.localUpload = false;
    // dialogStatus.value = Object.assign({}, initDialogStatus);
    // }, 1500);
  }
};

// 筛选资源列表按钮
const handleQuery = () => {
  getResourceList();
};

// 重置按钮
const resetQuery = () => {
  queryResource.value = Object.assign({}, initQueryResource);
  getResourceList();
};

// 获取资源列表
const getResourceList = async () => {
  if (resourceRegion.value === "0") {
    const res = await getSelfCourseResourceApi(queryResource.value);
    console.log(res);
    resourceList.value = res.rows;
    total.value = Number(res.total);
  } else if (resourceRegion.value === "1") {
    const res = await getPublicCourseResourceApi(queryResource.value);
    console.log(res);
    resourceList.value = res.rows;
    total.value = Number(res.total);
  } else {
    const res = await getAllCourseResourceApi(queryResource.value);
    console.log(res);
    resourceList.value = res.rows;
    total.value = Number(res.total);
  }
  resourceList.value.map((item: any) => {
    if (item.resourceStatus === 1) {
      item.resourceStatus = "上传成功";
    } else if (item.resourceStatus === 2) {
      item.resourceStatus = "上传失败";
    } else {
      item.resourceStatus = "上传中";
    }
  });
  resourceList.value.map((item: any) => {
    if (item.resourceType === "1") {
      item.resourceType = "视频";
    } else if (item.resourceType === "2") {
      item.resourceType = "音频";
    } else {
      item.resourceType = "文档";
    }
  });
};
// 资源状态设置
const statusType = (status: string) => {
  switch (status) {
    case "上传成功":
      return "success";
    case "上传失败,请联系管理员。":
      return "danger";
    case "上传中":
      return "info";
    default:
      return "";
  }
};

// 选择资源列表资源按钮
const chose = async (row: any) => {
  isPoolUpload.value = true;
  console.log(row);
  addChapter.value.resourceId = row.id;
  let vid: string = row.vid;
  const res = await getPlayAuthApi(vid);
  let playAuth = res.data.playAuth;
  nextTick(() => {
    if (vodPlayer.value) {
      console.log(vodPlayer.value);

      // 销毁之前已有的视频
      vodPlayer.value.dispose();
      vodPlayer.value = new Aliplayer({
        id: "myPlayer",
        width: "100%",
        vid: vid, //必选参数。音视频ID。示例：1e067a2831b641db90d570b6480f****。
        playauth: playAuth, //必选参数。音视频播放凭证。
        autoplay: false,
        preload: false,
      });
      dialogStatus.value.choseResource = false;
    } else {
      console.log(vodPlayer.value);

      vodPlayer.value = new Aliplayer({
        id: "myPlayer",
        width: "100%",
        vid: vid, //必选参数。音视频ID。示例：1e067a2831b641db90d570b6480f****。
        playauth: playAuth, //必选参数。音视频播放凭证。
        autoplay: false,
        preload: false,
      });
      dialogStatus.value.choseResource = false;
    }
  });
};

// 关闭uploadDialog
const closeUploadDialog = () => {
  dialogStatus.value.localUpload = false;
};

// 确定新增章节按钮
const finishAddChapter = async () => {
  console.log(addChapter.value);
  currentCourseId.value = addChapter.value.courseId;
  if ((addChapter.value as any).id) {
    // 有id是编辑
    console.log(2);

    await updateChapter();
  } else {
    // 没有id是新增
    console.log(1);

    const res = await addChapterApi(addChapter.value);
    console.log(res);
  }
  dialogStatus.value.addchapter = false;
  // 保存课程id
  console.log(addChapter.value);
  // currentCourseId.value = addchapter.value.courseId
  await getChapterList();
  addChapter.value.courseId = currentCourseId.value;
  console.log(addChapter.value);
};

// 关闭dialog回调
const closeDialog = () => {
  dialogStatus.value.addchapter = false;
  addChapter.value = Object.assign({}, initAddChapter);
};

// 获取章节列表
const getChapterList = async () => {
  const { rows } = await getChapterListApi(getChapterListBO.value);
  console.log(rows);
  if (rows) {
    // 如果有数据
    if (rows.length && rows.length > 0) {
      addChapter.value.orderNum = rows.length + 1;
    }
    courseChapterList.value = rows;
    for (let i = 0; i < courseChapterList.value.length; i++) {
      let vid: string = (courseChapterList.value[i] as any).vid;
      const res = await getPlayAuthApi(vid);
      let playAuth = res.data.playAuth;
      console.log((courseChapterList.value[i] as any).name);

      nextTick(() => {
        new Aliplayer({
          id: "play" + i + (courseChapterList.value[i] as any).name,
          width: "100%",
          vid: vid, //必选参数。音视频ID。示例：1e067a2831b641db90d570b6480f****。
          playauth: playAuth, //必选参数。音视频播放凭证。
          autoplay: false,
          preload: false,
        });
      });
    }
  } else {
    // 如果没有数据
    courseChapterList.value = [];
    addChapter.value.orderNum = 1;
  }
};

// 调整章节
const editChapter = async (id: string) => {
  console.log(id);
  const res2 = await getChapterDetailApi(id);
  console.log(res2);
  addChapter.value = res2.data;
  // 先创建dom再
  dialogStatus.value.addchapter = true;
  dialogStatus.value.title = "调整章节";
  let vid: string = (addChapter.value as any).vid;
  const res = await getPlayAuthApi(vid);
  let playAuth = res.data.playAuth;
  nextTick(() => {
    if (vodPlayer.value) {
      console.log(vodPlayer.value);

      // 销毁之前已有的视频
      vodPlayer.value.dispose();
      vodPlayer.value = new Aliplayer({
        id: "myPlayer",
        width: "100%",
        vid: vid, //必选参数。音视频ID。示例：1e067a2831b641db90d570b6480f****。
        playauth: playAuth, //必选参数。音视频播放凭证。
        autoplay: false,
        preload: false,
      });
    } else {
      console.log(vodPlayer.value);

      vodPlayer.value = new Aliplayer({
        id: "myPlayer",
        width: "100%",
        vid: vid, //必选参数。音视频ID。示例：1e067a2831b641db90d570b6480f****。
        playauth: playAuth, //必选参数。音视频播放凭证。
        autoplay: false,
        preload: false,
      });
    }
  });
};
// 前移章节
const forward = async (item: any) => {
  console.log(item);
  exchangeBO.value.sectionId1 = item.id;
  exchangeBO.value.sectionId2 = (
    courseChapterList.value[item.orderNum - 2] as any
  ).id;
  const res = await exchangeApi(exchangeBO.value);
  console.log(res);
  getChapterList();
};
// 后移章节
const back = async (item: any) => {
  exchangeBO.value.sectionId1 = item.id;
  exchangeBO.value.sectionId2 = (
    courseChapterList.value[item.orderNum] as any
  ).id;
  const res = await exchangeApi(exchangeBO.value);
  console.log(res);
  getChapterList();
};
// 删除章节
const delChapter = async (id: string) => {
  const res = await delChapterApi(id);
  console.log(res);
  getChapterList();
};

// 编辑章节
const updateChapter = async () => {
  // addChapter.value.updateTime = null
  console.log(addChapter.value);
  const res = await updataChpaterApi(addChapter.value);
  console.log(res);
};

// 上一步
const lastPage = () => {
  if (secondPage.value) {
    secondPage.value = false;
    firstPage.value = true;
  } else {
    secondPage.value = true;
    thirdPage.value = false;
  }
};

// 下一步
const next = () => {
  if (firstPage.value) {
    firstPage.value = false;
    secondPage.value = true;
  } else if (secondPage.value) {
    secondPage.value = false;
    firstPage.value = false;
    thirdPage.value = true;
  }
};

// 封面1选择

const handleSelectCover1 = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  console.log(uploadFile, uploadFiles);
  originalCoverFile1.value = uploadFile.raw;
  showCropDialog1();
};

const handleReselectCover1 = (files: File[], uploadFiles: UploadUserFile[]) => {
  console.log(files);
  // console.log(uploadFile, uploadFiles)
  originalCoverFile1.value = files[0];
  showCropDialog1();
};

const handleRecropCover1 = () => {
  // console.log(uploadFile, uploadFiles)
  showCropDialog1();
};

const showCropDialog1 = () => {
  const URL = window.URL || window.webkitURL;
  options1.img = URL.createObjectURL(originalCoverFile1.value);
  dialogStatus.value.isCropper1 = true;
};

// 封面2选择

const handleSelectCover2 = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  console.log(uploadFile, uploadFiles);
  originalCoverFile2.value = uploadFile.raw;
  showCropDialog2();
};

const handleReselectCover2 = (files: File[], uploadFiles: UploadUserFile[]) => {
  console.log(files);
  // console.log(uploadFile, uploadFiles)
  originalCoverFile2.value = files[0];
  showCropDialog2();
};

const handleRecropCover2 = () => {
  // console.log(uploadFile, uploadFiles)
  showCropDialog2();
};

const showCropDialog2 = () => {
  const URL = window.URL || window.webkitURL;
  options2.img = URL.createObjectURL(originalCoverFile2.value);
  dialogStatus.value.isCropper2 = true;
};

// 封面3选择

const handleSelectCover3 = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  console.log(uploadFile, uploadFiles);
  originalCoverFile3.value = uploadFile.raw;
  showCropDialog3();
};

const handleReselectCover3 = (files: File[], uploadFiles: UploadUserFile[]) => {
  console.log(files);
  // console.log(uploadFile, uploadFiles)
  originalCoverFile3.value = files[0];
  showCropDialog3();
};

const handleRecropCover3 = () => {
  // console.log(uploadFile, uploadFiles)
  showCropDialog3();
};

const showCropDialog3 = () => {
  const URL = window.URL || window.webkitURL;
  options3.img = URL.createObjectURL(originalCoverFile3.value);
  dialogStatus.value.isCropper3 = true;
};

const getUploadText = (status: boolean): string => {
  return status ? "已上传" : "确定上传";
};

onMounted(() => {});
</script>

<style lang="scss">
.introduceItem {
  margin-right: 20px;
}

.chapterItem {
  margin: 20px;
}

.section-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
  color: #333333;
  padding-bottom: 10px;
}

.image-buttons {
  margin-top: 16px;
}

.image-buttons-right {
  margin-left: 16px;
}

.cover1 {
  .el-upload--picture-card {
    width: 370px;
    height: 249px;
    overflow: hidden;
  }
}

.cover2 {
  .el-upload--picture-card {
    width: 170px;
    height: 230px;
    overflow: hidden;
  }
}

.cover3 {
  .el-upload--picture-card {
    width: 200px;
    height: 200px;
    overflow: hidden;
  }
}
</style>
